package com.adms.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.adms.domain.Message;
import com.adms.domain.MessageExample;
import com.adms.domain.MessageExample.Criteria;
import com.adms.domain.MessageMapper;
import com.adms.util.ShiroUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;

@Transactional
@Service
public class MessageService {

	@Autowired
	private MessageMapper messageMapper;

	public Message getByMessageId(Integer messageId) {
		return messageMapper.selectByPrimaryKey(messageId);
	}

	public PageInfo<Message> list(Message message, String timeField, Date start, Date end,
			String orderByClause, Integer pageNum, Integer pageSize, Integer navigatePages) {

		MessageExample ex = constructExample(message, timeField, start, end, orderByClause);
		PageHelper.startPage(pageNum, pageSize);
		List<Message> messages = messageMapper.selectByExample(ex);
		return new PageInfo<>(messages, navigatePages);
	}

	private MessageExample constructExample(Message message, String timeField, Date start, Date end,
			String orderByClause) {
		MessageExample ex = new MessageExample();
		Criteria or = ex.or();
		// 默认看自己
		or.andUserIdEqualTo(ShiroUtil.getUser().getUserId());
		if (message != null) {
			Integer reformId = message.getReformId();
			Integer replyId = message.getReplyId();
			Integer delayId = message.getDelayId();
			Integer executeId = message.getExecuteId();
			String type = message.getType();
			Boolean isClicked = message.getIsClicked();
			if (reformId != null) {
				or.andReformIdEqualTo(reformId);
			}
			if (replyId != null) {
				or.andReplyIdEqualTo(replyId);
			}
			if (delayId != null) {
				or.andDelayIdEqualTo(delayId);
			}
			if (executeId != null) {
				or.andExecuteIdEqualTo(executeId);
			}
			if (StringUtil.isNotEmpty(type)) {
				or.andTypeEqualTo(type);
			}
			if (isClicked != null) {
				or.andIsClickedEqualTo(isClicked);
			}
		}

		if (StringUtil.isNotEmpty(timeField)) {
			if (timeField.equals("createTime")) {
				if (start != null) {
					if (end != null) {
						or.andCreateTimeBetween(start, end);
					} else {
						or.andCreateTimeGreaterThanOrEqualTo(start);
					}
				} else {
					if (end != null) {
						or.andCreateTimeLessThanOrEqualTo(end);
					}
				}
			}
		}

		if (StringUtil.isNotEmpty(orderByClause)) {
			ex.setOrderByClause(orderByClause);
		} else {
			ex.setOrderByClause("message.create_time desc");
		}
		return ex;
	}

	public boolean click(Integer messageId) {
		Message message = new Message();
		message.setMessageId(messageId);
		message.setIsClicked(true);
		messageMapper.updateByPrimaryKeySelective(message);
		return true;
	}

}
